{% extends "admin/base.html" %}

{% block title %}分类管理{% endblock %}
{% block page_title %}分类管理{% endblock %}

{% block content %}
<div class="row">
    <!-- Add Category Form -->
    <div class="col-md-4">
        <div class="card shadow">
            <div class="card-header">
                <h5 class="mb-0">添加分类</h5>
            </div>
            <div class="card-body">
                <form method="POST">
                    {{ form.hidden_tag() }}
                    
                    <div class="mb-3">
                        {{ form.name.label(class="form-label") }}
                        {{ form.name(class="form-control") }}
                        {% if form.name.errors %}
                        <div class="text-danger">
                            {% for error in form.name.errors %}
                            <small>{{ error }}</small>
                            {% endfor %}
                        </div>
                        {% endif %}
                    </div>
                    
                    <div class="mb-3">
                        {{ form.description.label(class="form-label") }}
                        {{ form.description(class="form-control") }}
                        {% if form.description.errors %}
                        <div class="text-danger">
                            {% for error in form.description.errors %}
                            <small>{{ error }}</small>
                            {% endfor %}
                        </div>
                        {% endif %}
                    </div>
                    
                    <button type="submit" class="btn btn-primary">
                        <i class="fas fa-plus"></i> 添加分类
                    </button>
                </form>
            </div>
        </div>
    </div>

    <!-- Categories List -->
    <div class="col-md-8">
        <div class="card shadow">
            <div class="card-header">
                <h5 class="mb-0">分类列表</h5>
            </div>
            <div class="card-body">
                {% if categories %}
                <div class="table-responsive">
                    <table class="table table-hover">
                        <thead>
                            <tr>
                                <th>分类名称</th>
                                <th>描述</th>
                                <th>文章数量</th>
                                <th>创建时间</th>
                                <th>操作</th>
                            </tr>
                        </thead>
                        <tbody>
                            {% for category in categories %}
                            <tr>
                                <td>
                                    <strong>{{ category.name }}</strong>
                                    <br><small class="text-muted">{{ category.slug }}</small>
                                </td>
                                <td>
                                    {% if category.description %}
                                    {{ category.description[:50] }}{% if category.description|length > 50 %}...{% endif %}
                                    {% else %}
                                    <span class="text-muted">无描述</span>
                                    {% endif %}
                                </td>
                                <td>
                                    <span class="badge bg-primary">{{ category.posts.filter_by(is_published=True).count() }}</span>
                                </td>
                                <td>{{ category.created_at.strftime('%Y-%m-%d') }}</td>
                                <td>
                                    <div class="btn-group btn-group-sm" role="group">
                                        <a href="{{ url_for('main.category_posts', slug=category.slug) }}" 
                                           class="btn btn-outline-info" target="_blank">
                                            <i class="fas fa-eye"></i>
                                        </a>
                                        <button type="button" class="btn btn-outline-warning" 
                                                onclick="editCategory({{ category.id }}, '{{ category.name }}', '{{ category.description or '' }}')">
                                            <i class="fas fa-edit"></i>
                                        </button>
                                        <button type="button" class="btn btn-outline-danger" 
                                                onclick="deleteCategory({{ category.id }}, '{{ category.name }}')">
                                            <i class="fas fa-trash"></i>
                                        </button>
                                    </div>
                                </td>
                            </tr>
                            {% endfor %}
                        </tbody>
                    </table>
                </div>
                {% else %}
                <div class="text-center py-4">
                    <i class="fas fa-folder fa-3x text-muted mb-3"></i>
                    <h5 class="text-muted">还没有分类</h5>
                    <p class="text-muted">添加第一个分类来组织你的文章。</p>
                </div>
                {% endif %}
            </div>
        </div>
    </div>
</div>

<!-- Edit Category Modal -->
<div class="modal fade" id="editCategoryModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">编辑分类</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <form id="editCategoryForm">
                <div class="modal-body">
                    <div class="mb-3">
                        <label for="editName" class="form-label">分类名称</label>
                        <input type="text" class="form-control" id="editName" required>
                    </div>
                    <div class="mb-3">
                        <label for="editDescription" class="form-label">描述</label>
                        <textarea class="form-control" id="editDescription" rows="3"></textarea>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="submit" class="btn btn-primary">保存更改</button>
                </div>
            </form>
        </div>
    </div>
</div>
{% endblock %}

{% block extra_js %}
<script>
let editingCategoryId = null;

function editCategory(id, name, description) {
    editingCategoryId = id;
    document.getElementById('editName').value = name;
    document.getElementById('editDescription').value = description;
    
    const modal = new bootstrap.Modal(document.getElementById('editCategoryModal'));
    modal.show();
}

function deleteCategory(id, name) {
    if (confirm(`确定要删除分类"${name}"吗？\n\n注意：删除分类不会删除该分类下的文章，但文章将变为未分类状态。`)) {
        fetch(`/admin/categories/${id}/delete`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            }
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                alert(data.message);
                location.reload(); // 重新加载页面
            } else {
                alert('删除失败：' + data.message);
            }
        })
        .catch(error => {
            console.error('删除分类失败:', error);
            alert('删除失败，请重试');
        });
    }
}

document.getElementById('editCategoryForm').addEventListener('submit', function(e) {
    e.preventDefault();
    
    if (!editingCategoryId) return;
    
    const name = document.getElementById('editName').value.trim();
    const description = document.getElementById('editDescription').value.trim();
    
    if (!name) {
        alert('分类名称不能为空');
        return;
    }
    
    fetch(`/admin/categories/${editingCategoryId}/edit`, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify({ 
            name: name,
            description: description
        })
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            alert(data.message);
            location.reload(); // 重新加载页面
        } else {
            alert('更新失败：' + data.message);
        }
    })
    .catch(error => {
        console.error('更新分类失败:', error);
        alert('更新失败，请重试');
    });
    
    // 关闭模态框
    const modal = bootstrap.Modal.getInstance(document.getElementById('editCategoryModal'));
    modal.hide();
});
</script>
{% endblock %}

